//
//  GeneralModel.swift
//  GerritHermes
//
//  Created by J.Zhou on 2019/12/30.
//  Copyright © 2019 J.Zhou. All rights reserved.
//

import Foundation
import SwiftUI

private extension String {
    static let address = "address"
    static let username = "username"
    static let credential = "credential"
    static let interval = "interval"
    static let admin = "admin"
}

final class GeneralModel: ObservableObject {
    static let shared = GeneralModel()

    private let bag = CancellableBag()
    @Published var gerritAddress = ""
    @Published var username = ""
    @Published var credential = ""
    @Published var interval: TimeInterval = 60

    private init() {
        do {
            gerritAddress = try SimpleStore.object(for: .address) ?? "https://gerrit.zhenguanyu.com"
            username = try SimpleStore.object(for: .username) ?? ""
            credential = try SimpleStore.object(for: .credential) ?? ""
            interval = try SimpleStore.object(for: .interval) ?? 60
        } catch let error {
            Log.error("读取配置失败", context: error)
        }

        objectWillChange
            .delay(for: .milliseconds(300), scheduler: DispatchQueue.main)
            .sink {
                do {
                    try SimpleStore.set(self.gerritAddress, for: .address)
                    try SimpleStore.set(self.username, for: .username)
                    try SimpleStore.set(self.credential, for: .credential)
                    try SimpleStore.set(self.interval, for: .interval)
                } catch let error {
                    Log.error("写入配置失败", context: error)
                }
            }.cancel(by: bag)
    }

    func update() {

    }
}
